package com.maben.security.controller;

import com.maben.security.pojo.UserPO;
import com.maben.security.service.UserService;
import com.maben.security.util.JwtUtils;
import com.maben.security.util.RedisTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户controller
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private JwtUtils jwtUtils;

    //    登录接口
    @RequestMapping(value = "doLogin", method = RequestMethod.POST)
    public Map<String, Object> doLogin(String username, String password) {
        final Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        try {
            if (StringUtils.isBlank(username)) {
                throw new Exception("用户名为空");
            }
            // 1. 调用 Spring Security 认证管理器验证用户名密码
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password)
            );
            // 2. 认证成功，生成 Token
            String token = jwtUtils.generateToken(username);
            result.put("msg", "登录成功");
            result.put("token", token);
            log.info("{}:登录成功", username);
        } catch (Exception e) {
            result.put("code", -1);
            result.put("msg", ExceptionUtils.getStackTrace(e));
        }
        return result;
    }

    @Resource
    private RedisTokenUtils redisTokenUtils;
    @Resource
    private UserService userService;
    @Resource // 注入密码编码器（Spring Security 自动配置的 BCryptPasswordEncoder）
    private PasswordEncoder passwordEncoder;
    /**
     * 登录接口
     */
    @PostMapping("/login")
    public Map<String, Object> login(String username, String password) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        try {
            // 1. 验证用户名密码（实际需调用userDetailsService并比对密码）
            final UserPO byUsername = userService.getByUsername(username);
            if (byUsername == null) {
                throw new RuntimeException("用户名失效");
            }
            if (!passwordEncoder.matches(password, byUsername.getPassword())) {
                // 密码不匹配
                throw new RuntimeException("用户名或密码错误");
            }
            // 2. 生成Token并返回
            String token = redisTokenUtils.generateToken(username);
            result.put("token", token);
            result.put("msg", "登录成功");
        } catch (Exception e) {
            result.put("code", 400);
            result.put("msg", ExceptionUtils.getStackTrace(e));
            log.error("登录报错:{}",ExceptionUtils.getStackTrace(e));
        }
        return result;
    }

    /**
     * 登出接口
     */
    @PostMapping("/logout")
    public Map<String, Object> logout(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            redisTokenUtils.logout(token); // 删除Redis中的Token
        }
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "登出成功");
        return result;
    }
}
